package org.example.system.common.util;

import cn.hutool.core.lang.Snowflake;
import cn.hutool.core.net.NetUtil;
import cn.hutool.core.util.IdUtil;
import jakarta.annotation.PostConstruct;
import org.springframework.stereotype.Component;

import java.util.concurrent.atomic.AtomicInteger;

@Component
public class OrderSnGenerator {
    private Snowflake snowflake;
    private final AtomicInteger dataCenterId = new AtomicInteger(0);
    private final AtomicInteger workerId = new AtomicInteger(0);

    @PostConstruct
    public void init() {
        // 获取本地IP地址的哈希值作为数据中心ID的一部分
        Long dataCenterIdValue = Math.abs(NetUtil.ipv4ToLong(NetUtil.getLocalhostStr()) % 32);
        dataCenterId.set(dataCenterIdValue.intValue());
        // 以进程ID作为工作机器ID的一部分
        Long workerIdValue = Math.abs(Thread.currentThread().getId() % 32);
        workerId.set(workerIdValue.intValue());
        snowflake = IdUtil.getSnowflake(workerId.get(), dataCenterId.get());
    }

    public String makeOrderNumber() {
        return snowflake.nextIdStr();
    }
}
